#!/bin/bash

# 飞书机器人CentOS 7.9专用部署脚本
# 使用兼容的Node.js版本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示欢迎信息
show_welcome() {
    echo ""
    echo "🚀 飞书机器人CentOS 7.9专用部署脚本"
    echo "服务器: 47.120.11.77 (CentOS 7.9)"
    echo "=================================="
    echo ""
}

# 检查SSH密钥
check_ssh_keys() {
    print_info "检查SSH密钥..."
    
    if [ ! -f ~/.ssh/id_rsa.pub ]; then
        print_error "未找到SSH公钥"
        echo "请先生成SSH密钥对："
        echo "ssh-keygen -t rsa -b 4096 -C 'your-email@example.com'"
        exit 1
    fi
    
    print_success "SSH密钥检查通过"
}

# 配置SSH密钥
setup_ssh() {
    print_info "配置SSH密钥..."
    
    # 检查是否已经配置
    if ssh -o ConnectTimeout=5 -o BatchMode=yes feishu-server "echo 'SSH已配置'" 2>/dev/null; then
        print_success "SSH密钥已配置"
        return 0
    fi
    
    # 获取服务器密码
    echo ""
    print_warning "需要服务器root密码来配置SSH密钥"
    read -s -p "请输入服务器root密码: " SERVER_PASSWORD
    echo ""
    
    if [ -z "$SERVER_PASSWORD" ]; then
        print_error "密码不能为空"
        return 1
    fi
    
    # 安装sshpass
    if ! command -v sshpass &> /dev/null; then
        print_info "安装sshpass..."
        if command -v brew &> /dev/null; then
            brew install sshpass
        else
            print_error "请手动安装sshpass: brew install sshpass"
            return 1
        fi
    fi
    
    # 配置SSH密钥
    LOCAL_PUBLIC_KEY=$(cat ~/.ssh/id_rsa.pub)
    
    sshpass -p "$SERVER_PASSWORD" ssh -o StrictHostKeyChecking=no root@47.120.11.77 << 'EOF'
        mkdir -p ~/.ssh
        chmod 700 ~/.ssh
        touch ~/.ssh/authorized_keys
        chmod 600 ~/.ssh/authorized_keys
EOF
    
    echo "$LOCAL_PUBLIC_KEY" | sshpass -p "$SERVER_PASSWORD" ssh -o StrictHostKeyChecking=no root@47.120.11.77 "cat >> ~/.ssh/authorized_keys"
    
    print_success "SSH密钥配置完成"
}

# 安装Node.js 14.x（兼容CentOS 7.9）
install_nodejs() {
    print_info "安装Node.js 14.x（兼容CentOS 7.9）..."
    
    # 清理旧的Node.js源
    ssh feishu-server "rm -f /etc/yum.repos.d/nodesource*"
    
    # 安装Node.js 14.x
    ssh feishu-server "curl -fsSL https://rpm.nodesource.com/setup_14.x | bash -"
    ssh feishu-server "yum install -y nodejs"
    
    # 验证安装
    NODE_VERSION=$(ssh feishu-server "node --version")
    print_success "Node.js安装完成: $NODE_VERSION"
}

# 部署应用
deploy_app() {
    print_info "部署飞书机器人应用..."
    
    # 服务器环境配置
    print_info "配置服务器环境..."
    ssh feishu-server "yum update -y"
    ssh feishu-server "yum install -y curl wget git vim nginx"
    
    # 安装Node.js
    install_nodejs
    
    # 安装PM2
    ssh feishu-server "npm install -g pm2"
    
    # 防火墙配置
    print_info "配置防火墙..."
    ssh feishu-server "systemctl enable firewalld"
    ssh feishu-server "systemctl start firewalld"
    ssh feishu-server "firewall-cmd --permanent --add-service=ssh"
    ssh feishu-server "firewall-cmd --permanent --add-service=http"
    ssh feishu-server "firewall-cmd --permanent --add-service=https"
    ssh feishu-server "firewall-cmd --permanent --add-port=3000/tcp"
    ssh feishu-server "firewall-cmd --reload"
    
    # Nginx配置
    print_info "配置Nginx..."
    cat > nginx-feishu.conf << 'EOF'
server {
    listen 80;
    server_name 47.120.11.77;
    
    location /webhook/ {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        proxy_connect_timeout 5s;
        proxy_send_timeout 5s;
        proxy_read_timeout 5s;
    }
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF
    
    scp nginx-feishu.conf feishu-server:/etc/nginx/conf.d/feishu-robot.conf
    ssh feishu-server "nginx -t && systemctl enable nginx && systemctl restart nginx"
    rm nginx-feishu.conf
    
    # 应用部署
    print_info "部署应用..."
    ssh feishu-server "mkdir -p /opt/feishu-robot"
    scp -r src/ feishu-server:/opt/feishu-robot/
    scp package.json feishu-server:/opt/feishu-robot/
    scp config.js feishu-server:/opt/feishu-robot/
    
    ssh feishu-server "cd /opt/feishu-robot && npm install --production"
    
    # PM2配置
    cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [{
    name: 'feishu-robot',
    script: 'src/app.js',
    cwd: '/opt/feishu-robot',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: '/opt/feishu-robot/logs/err.log',
    out_file: '/opt/feishu-robot/logs/out.log',
    log_file: '/opt/feishu-robot/logs/combined.log',
    time: true
  }]
};
EOF
    
    scp ecosystem.config.js feishu-server:/opt/feishu-robot/
    ssh feishu-server "mkdir -p /opt/feishu-robot/logs"
    ssh feishu-server "cd /opt/feishu-robot && pm2 start ecosystem.config.js"
    ssh feishu-server "pm2 save"
    ssh feishu-server "pm2 startup"
    rm ecosystem.config.js
    
    print_success "应用部署完成"
}

# 测试部署
test_deployment() {
    print_info "测试部署..."
    
    sleep 5
    
    # 测试健康检查
    if curl -s http://47.120.11.77/webhook/health | grep -q "服务正常运行"; then
        print_success "健康检查通过"
    else
        print_error "健康检查失败"
        return 1
    fi
    
    # 测试webhook端点
    if curl -s http://47.120.11.77/webhook/feishu -X POST -H "Content-Type: application/json" -d '{"type":"test"}' | grep -q "success"; then
        print_success "Webhook端点测试通过"
    else
        print_error "Webhook端点测试失败"
        return 1
    fi
    
    print_success "部署测试完成"
}

# 显示部署信息
show_deployment_info() {
    echo ""
    echo "🎉 飞书机器人部署完成！"
    echo ""
    echo "📋 部署信息："
    echo "   服务器IP: 47.120.11.77"
    echo "   应用端口: 3000"
    echo "   Webhook地址: http://47.120.11.77/webhook/feishu"
    echo "   健康检查: http://47.120.11.77/webhook/health"
    echo ""
    echo "🔧 管理命令："
    echo "   查看应用状态: ssh feishu-server 'pm2 status'"
    echo "   查看日志: ssh feishu-server 'pm2 logs feishu-robot'"
    echo "   重启应用: ssh feishu-server 'pm2 restart feishu-robot'"
    echo "   停止应用: ssh feishu-server 'pm2 stop feishu-robot'"
    echo ""
    echo "📝 飞书配置："
    echo "   在飞书开发者后台配置："
    echo "   请求网址: http://47.120.11.77/webhook/feishu"
    echo "   Encrypt Key: QoMazhHf0AoOd2miHeoK7gT4aFASztop"
    echo "   Verification Token: tKE5o4Swsu4bN9lrrOe7rerCbrAJM4l7"
    echo ""
    echo "⚠️  注意事项："
    echo "   1. 使用Node.js 14.x版本（兼容CentOS 7.9）"
    echo "   2. 生产环境建议配置HTTPS"
    echo "   3. 定期备份应用数据"
    echo "   4. 监控服务器资源使用情况"
}

# 主函数
main() {
    show_welcome
    
    # 检查SSH密钥
    check_ssh_keys
    
    # 配置SSH密钥
    if ! setup_ssh; then
        print_error "SSH配置失败"
        exit 1
    fi
    
    # 部署应用
    deploy_app
    
    # 测试部署
    if test_deployment; then
        show_deployment_info
    else
        print_error "部署测试失败，请检查服务器配置"
        exit 1
    fi
}

# 运行主函数
main "$@" 